package HuffmanTree;

import java.io.*;
import java.util.Arrays;

public class HuffmanTest {
    public static void main(String[] args) throws IOException {


        //把字符集从文件中读出来，并保存在一个数组characters里面
        File file = new File("C:\\Users\\24098\\duan_zhixuan_20172304java\\untitled\\src\\HuffmanTree\\text.txt");
        Reader reader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String temp = bufferedReader.readLine();

        char characters[] = new char[temp.length()];
        for (int i = 0; i < temp.length(); i++) {
            characters[i] = temp.charAt(i);
        }
        System.out.println("原字符集为：" + Arrays.toString(characters));
        //计算每一个字符出现的频率。用嵌套循环来实现，并把出现的概率存在另一个数组中
        double frequency[] = new double[27];
        int numbers = 0;//空格的个数
        for (int i = 0; i < characters.length; i++) {
            if (characters[i] == ' ') {
                numbers++;
            }
            frequency[26] = (float) numbers / characters.length;
        }
        System.out.println("字符集为");
        for (int j = 97; j <= 122; j++) {
            int number = 0;//给字母计数
            for (int m = 0; m < characters.length; m++) {
                if (characters[m] == (char) j) {
                    number++;
                }
                frequency[j - 97] = (float) number / characters.length;
            }
            System.out.print((char) j + "，");
        }
        System.out.println("空");
        System.out.println("每一个字符对应的概率为（从a到z还有一个空格）" + "\n" + Arrays.toString(frequency));
        double result = 0.0;
        for (int z = 0; z < 27; z++) {
            result += frequency[z];
        }
        System.out.println("总概率之和为" + result);


        Huffman huff = new Huffman();// 创建哈弗曼对象

            String data = "come on bay"; // 读取本地文件（自己写的方法，不想写可以自己随便定一个字符串）
            huff.creatHfmTree(temp);// 构造树



            // 将目标字符串利用生成好的哈夫曼编码生成对应的二进制编码
            String hufmCode = huff.toHufmCode(temp);
            System.out.println("编码:" + hufmCode);

            // 将上述二进制编码再翻译成字符串
            System.out.println("解码：" + huff.CodeToString(hufmCode));
        }
    }

